package sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: 杰哥
 * Date: 2020/4/5
 * Time: 17:00
 * 插入排序
 */
public class InsertSort {
    public static void main(String[] args) {
        int arr[] = new int[200000];
        for (int i = 0; i < 200000; i++) {
            arr[i] = (int)(Math.random() * 200000);
        }
        Date date1 = new Date();
        insertSort(arr);
        Date date2 = new Date();
        System.out.println("用时：" + (date2.getTime() - date1.getTime()) + "毫秒" );
//        System.out.println(Arrays.toString(arr));
    }

    public static void insertSort(int[] arr) {
        //  记录当前要插入的值
        int insertVal;
        //  记录当前要插入的值的前一个值的下标
        int insertIndex;
        for (int i = 1; i < arr.length; i++) {
            insertVal = arr[i];
            insertIndex = i - 1;
            while (insertIndex >= 0 && insertVal < arr[insertIndex] ) {
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex--;
            }
            arr[insertIndex + 1] = insertVal;
        }
    }
}
